<template>
    <div class="box">
        <!-- <div class="box-left">
            <img src="../assets/NewLogin/01.png" alt="">
        </div> -->
        <div class="box-left">
          <el-carousel
            height="100%"
            indicator-position="none"
            arrow="never"
            :interval="2000"
            motion-blur
          >
            <el-carousel-item v-for="(src, idx) in bannerList" :key="idx">
              <img :src="src" alt="banner" />
            </el-carousel-item>
          </el-carousel>
        </div>
        <div class="box-right">
            <div class="box-right-top">
                <img src="../assets/NewLogin/02.png" alt="">
            </div>
            <div class="box-right-center">
                <!-- <h2>{{ businessLogin ? '登录商家后台' : '登录金诺云展管理后台' }}</h2> -->
                <h2
                    v-if="domain && (domain.indexOf('console.noctech.cn') >= 0 || domain.indexOf('console.nocexpo.com') >= 0)">
                    登录金诺云展管理后台</h2>
                <h2 v-else>登录供应商后台</h2>
                <el-form :model="login" :rules="passwordLoginRules" ref="formRef" v-if="passwordLogin === true" @keyup.enter="onVerify">
                    <el-form-item prop="username">
                        <el-input class="login-input" v-model="login.username" placeholder="请输入用户名"
                            :suffix-icon="usernameSuffixIcon" @blur="validateUsername">
                            <template #prefix>
                                <img src="@/assets/NewLogin/05.png"
                                    style="width: 25px; height: 25px; object-fit: contain;padding-right: 10px;border-right: 1px solid #d3dceb;" />
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item prop="password">
                        <el-input class="login-input" v-model="login.password" placeholder="请输入密码" show-password
                            :suffix-icon="passwordSuffixIcon" @blur="validatePassword">
                            <template #prefix>
                                <img src="@/assets/NewLogin/04.png"
                                    style="width: 25px; height: 25px; object-fit: contain;padding-right: 10px;border-right: 1px solid #d3dceb;" />
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-checkbox v-model="form.remember">记住密码</el-checkbox>
                    </el-form-item>
                    <el-form-item prop="login">
                        <el-button class="login-btn" type="primary" :disabled="state.loading" @click="onVerify">登 录</el-button>
                    </el-form-item>
                </el-form>
                <el-form :model="login" :rules="codeLoginRules" ref="formRef" v-if="passwordLogin === false" @keyup.enter="onVerify">
                    <el-form-item prop="username">
                        <el-input class="login-input" v-model="login.username" placeholder="请输入手机号码">
                            <template #prefix>
                                <img src="@/assets/NewLogin/03.png"
                                    style="width: 25px; height: 25px; object-fit: contain;padding-right: 10px;border-right: 1px solid #d3dceb;" />
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item prop="phoneVerCode">
                        <el-input class="login-input login-input-append" v-model="login.phoneVerCode" placeholder="请输入验证码">
                            <template #prefix>
                                <img src="@/assets/NewLogin/04.png"
                                    style="width: 25px; height: 25px; object-fit: contain;padding-right: 10px;border-right: 1px solid #d3dceb;" />
                            </template>
                            <template #append>
                                <span @click="getCode" :disabled="state.countdown > 0" style="cursor: pointer;">
                                    {{ state.countdown > 0 ? `${state.countdown}秒后重试` : '获取验证码' }}
                                </span>
                            </template>
                        </el-input>
                    </el-form-item>
                    <!-- <el-form-item>
                        <el-checkbox v-model="form.remember">记住密码</el-checkbox>
                    </el-form-item> -->
                    <el-form-item prop="login">
                        <el-button class="login-btn" type="primary" :disabled="state.loading" @click="onVerify">登 录</el-button>
                    </el-form-item>
                </el-form>
                <p v-if="domain && (domain.indexOf('console.noctech.cn') >= 0 || domain.indexOf('console.nocexpo.com') >= 0)"
                    class="box-right-center-p" @click="passwordLogin = !passwordLogin; changeLoginMethod()"></p>
                <p v-else class="box-right-center-p" @click="passwordLogin = !passwordLogin; changeLoginMethod()">{{
                    passwordLogin ?
                        '验证码登录' : '密码登录' }}</p>

            </div>
            <div class="box-right-bottom">
                <!-- <el-button type="primary" @click="businessLogin = !businessLogin"
                    style="position: absolute;bottom: 0;right: 0;">切换</el-button> -->
            </div>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted, onBeforeUnmount, reactive } from 'vue';
import { CircleCheck, CircleClose } from '@element-plus/icons-vue';
import { CacheToken } from "@/constants/cacheKey";
import baseService from "@/service/baseService";
import { setCache } from "@/utils/cache";
import { ElMessage } from "element-plus";
import { getUuid } from "@/utils/utils";
import app from "@/constants/app";
import { useAppStore } from "@/store";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import { sliderVerification, ApplySlider } from "@/utils/sliderValidator";

declare const TencentCaptcha: any;

const store = useAppStore();
const router = useRouter();
const { t } = useI18n();


// 在 <script setup> 里加一行
const bannerList = ref([
  new URL('@/assets/NewLogin/01.png', import.meta.url).href,
  // new URL('@/assets/NewLogin/02.png', import.meta.url).href,
  // new URL('@/assets/NewLogin/01.png', import.meta.url).href, // 再准备几张图即可
])

//获取域名
const domain = ref();
const getDomain = () => {
    domain.value = window.location.host;
    console.log(domain.value)
}

// 是否是密码登录
const passwordLogin = ref(true)

// 状态管理
const state = reactive({
  captchaUrl: "",
  loading: false,
  year: new Date().getFullYear(),
  countdown: 0,
  timer: null as any
});

// 登录表单数据
const login = reactive({
  username: "",
  password: "",
  phoneVerCode: "",
  uuid: "",
  type: 0,
  randstr: "",
  ticket: '',
  loginType: 2  //1验证码登录 2密码登录
});

// 表单数据（保持原有结构以兼容UI）
const form = ref({
    username: '',
    password: '',
    phone: '',
    code: '',
    remember: false
})

// 校验状态
const usernameError = ref(false)
const passwordError = ref(false)

//滑块验证器
let applySlider: ApplySlider

// 密码登录校验规则
const passwordLoginRules = ref({
    username: [{ required: true, message: t("validate.required"), trigger: "blur" }],
    password: [{ required: true, message: t("validate.required"), trigger: "blur" }],
})

// 验证码登录校验规则
const codeLoginRules = ref({
    username: [{ required: true, message: t("validate.required"), trigger: "blur" }],
    phoneVerCode: [{ required: true, message: t("validate.required"), trigger: "blur" }],
})

// 当前使用的校验规则
const rules = computed(() => {
    return passwordLogin.value ? passwordLoginRules.value : codeLoginRules.value
})

const formRef = ref(null) as any

// 计算用户名后缀图标
const usernameSuffixIcon = computed(() => {
    if (login.username.length > 0) {
        return CircleCheck
    } else if (usernameError.value) {
        return CircleClose
    }
    return null
})

// 计算密码后缀图标
const passwordSuffixIcon = computed(() => {
    if (login.password.length > 0) {
        return CircleCheck
    } else if (passwordError.value) {
        return CircleClose
    }
    return null
})

// 校验用户名
const validateUsername = () => {
    if (login.username.length === 0) {
        usernameError.value = true
    } else {
        usernameError.value = false
    }
}

// 校验密码
const validatePassword = () => {
    if (login.password.length === 0) {
        passwordError.value = true
    } else {
        passwordError.value = false
    }
}

// 获取验证码方法
const getCode = () => {
  if (!login.username) {
    ElMessage.warning('请输入手机号或邮箱');
    return;
  }
  baseService.get("sys/user/ifNocUserExistByPhone", {
    username: login.username
  }).then(res => {
    if (res.code === 0) {
      let captcha =  new TencentCaptcha("194163642", (res:any)=>{
        if (res.ret === 0) {
          startCountdown();
          baseService.post(`/h5/testDescribeCaptchaResult`,{
            randstr: res.randstr,
            ticket: res.ticket,
            phone:login.username,
          }).then(res=>{
            if (res.code == 0 && (res as any).CaptchaCode == 1){
              ElMessage.success("发送验证码成功")
            }else{
              ElMessage.error("验证失败")
            }
          })
        }
      });
      captcha.show();
    } else {
      ElMessage.error(res.msg || '验证码发送失败');
    }
  }).catch(err => {
    ElMessage.error('验证码发送失败');
  });
};

// 开始验证
async function onVerify() {
  // 先进行表单验证
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      // 表单验证通过后，再进行图形验证
      applySlider().then((res) => {
        console.log('SliderValidatorResult:', res)
        if (res.ret === 0) {
          login.randstr = res.randstr;
          onLogin();
        }
      }).catch((error) => {
        console.error('图形验证失败:', error);
      });
    }
  });
};

const getCaptchaUrl = () => {
  login.uuid = getUuid();
  state.captchaUrl = `${app.api}/captcha?uuid=${login.uuid}`;
};

const onRefreshCode = () => {
  getCaptchaUrl();
};

const onLogin = () => {
  //loginType  1验证码登录 2密码登录
  state.loading = true;
  if (login.loginType == 1){
    loginByAuthCode();
    return;
  }
  baseService
    .post("/sys/login", login)
    .then((res) => {
      state.loading = false;
      if (res.code === 0) {
        setCache(CacheToken, res.data, true);
        //把账号密码写入到localStorage
        localStorage.setItem("username", login.username);
        localStorage.setItem("password", login.password);
        ElMessage.success(t("ui.login.loginOk"));
        router.push("/");
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {
      state.loading = false;
      onRefreshCode();
    });
};

function loginByAuthCode() {
  if (!login.username) {
    ElMessage.error("请输入手机号");
    return;
  }
  if (!login.phoneVerCode) {
    ElMessage.error("请输入手机验证码");
    return;
  }
  state.loading = true;
  // loginType=1验证码登录
  baseService.post("sys/login", {
    username: login.username,
    phoneVerCode: login.phoneVerCode,
    loginType: 1
  }).then(res => {
    state.loading = false;
    if (res.code === 0) {
      setCache(CacheToken, res.data, true);
      //把账号密码写入到localStorage
      localStorage.setItem("username", login.username);
      localStorage.setItem("password", login.password);
      ElMessage.success(t("ui.login.loginOk"));
      router.push("/");
    } else {
      ElMessage.error(res.msg);
    }
  }) .catch(() => {
    ElMessage.error("登录失败");
  })
    .finally(() => {
      state.loading = false;
    });
};

// 开始倒计时
const startCountdown = () => {
  state.countdown = 60;
  state.timer = setInterval(() => {
    state.countdown--;
    if (state.countdown <= 0 && state.timer) {
      clearInterval(state.timer);
      state.timer = null;
    }
  }, 1000);
};

// 切换登录方式
const changeLoginMethod = () => {
  login.password = '';
  login.phoneVerCode = '';
  // 更新登录类型：true为密码登录(2)，false为验证码登录(1)
  login.loginType = passwordLogin.value ? 2 : 1;
};

// 登录方法（保持原有接口）
const handleLogin = () => {
  onVerify();
}

/**
 * 禁止缩放
 */
// 阻止双击缩放
const handleDblClick = (e: Event) => {
    e.preventDefault()
}

// 阻止触摸缩放
const handleTouchStart = (e: TouchEvent) => {
    if (e.touches.length > 1) {
        e.preventDefault()
    }
}

// 阻止触摸移动缩放
const handleTouchMove = (e: TouchEvent) => {
    if (e.touches.length > 1) {
        e.preventDefault()
    }
}

// 阻止缩放
const handleScale = (e: WheelEvent) => {
    e.preventDefault()
}
onMounted(() => {
    getDomain();
    //清理数据
    store.logout();
    getCaptchaUrl();
    //初始化滑块验证器
    applySlider = sliderVerification();
    sessionStorage.removeItem('AUTH_TIP_SHOWN'); // ★ 先清，保证登录前一定不标记

    // 添加事件监听
    document.addEventListener('dblclick', handleDblClick, { passive: false })
    document.addEventListener('touchstart', handleTouchStart, { passive: false })
    document.addEventListener('touchmove', handleTouchMove, { passive: false })
    document.addEventListener('wheel', handleScale, { passive: false })
})

onUnmounted(() => {
    // 移除事件监听
    document.removeEventListener('dblclick', handleDblClick)
    document.removeEventListener('touchstart', handleTouchStart)
    document.removeEventListener('touchmove', handleTouchMove)
    document.removeEventListener('wheel', handleScale)
})

// 组件卸载时清除定时器
onBeforeUnmount(() => {
  if (state.timer) {
    clearInterval(state.timer);
    state.timer = null;
  }
});
</script>
<style lang="scss" scoped>
.box {
    width: 100vw;
    height: 100vh;
    // background-color: skyblue;
    display: flex;

    // .box-left {
    //     width: 50%;
    //     // height: 100vh;
    //     height: 100%;
    //     // background-color: skyblue;
    //     overflow: hidden;

    //     // vertical-align: bottom;
    //     img {
    //         width: 100%;
    //         height: 100%;
    //         object-fit: cover;
    //         // height: 100%;
    //         // margin-top: -5vh;
    //     }
    // }
        .box-left {
            width: 50%;
            height: 100%;
            overflow: hidden;

            .el-carousel,
            .el-carousel__container,
            .el-carousel__item {
              height: 100% !important;
            }

            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }
        }

    .box-right {
        width: 50%;
        // width: 50vw;
        // height: 100vh;
        height: 100%;
        background-color: #fff;
        // overflow: hidden;
        position: relative;

        .box-right-top {
            // width: 100%;
            // height: 100px;
            width: 50vw;
            height: 10vh;
            // background-color: #fff;

            // 怎么做放大缩小图片保持不变形
            img {
                object-fit: left;
                margin-top: 20px;
                margin-left: 20px;
            }
        }

        .box-right-center {
            // width: 100%;
            // height: 100%;
            // width: 50vw;
            // height:50vh;
            width: 400px;
            // height: 50vh;
            // height: 400px;
            // background-color: #fff;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);

            h2 {
                text-align: center;
                font-size: 22px;
                color: #373737;
                margin-top: 0px;
                margin-bottom: 80px;
                font-weight: bold;
            }

            .el-form {
                width: 396px;
                margin: 0 auto;

                // background-color: seagreen;
                .el-form-item {
                    margin-bottom: 34px;

                    :deep(.login-input) {
                        width: 396px;
                        height: 50px;

                        .el-input__wrapper {
                            border-radius: 6px;
                            background-color: #f3f6f8;
                        }

                        .el-input__inner {
                            font-size: 18px;
                            // color: #979ea5;
                        }

                        .el-input__inner::placeholder {
                            color: #979ea5;
                        }
                    }

                    :deep(.login-input-append) {
                        .el-input__wrapper {
                            border-radius: 6px 0 0 6px;
                        }

                        .el-input-group__append {
                            border-radius: 0 6px 6px 0;
                            background: linear-gradient(109.28deg, #4C9CFF 0%, #3C72EE 100%);
                            color: #fff;
                            border: none;
                            cursor: pointer;
                        }
                    }

                    // 修改校验错误提示样式
                    :deep(.el-form-item__error) {
                        font-size: 14px;
                        color: #ff5b2f;
                        margin-top: 5px;
                    }

                    // 修改输入框错误状态样式
                    :deep(.el-form-item.is-error .el-input__wrapper) {
                        border-color: #ff5b2f;
                        box-shadow: 0 0 0 1px #ff5b2f inset;
                    }
                }

                .login-btn {
                    width: 396px;
                    height: 58px;
                    background: linear-gradient(109.28deg, #4C9CFF 0%, #3C72EE 100%);
                    font-style: 20px;
                    font-weight: bold;
                    border-radius: 6px;
                    font-size: 18px;
                }
            }

            .box-right-center-p {
                text-align: center;
                font-size: 18px;
                color: #3F74F2;
                margin-top: 20px;
                cursor: pointer;
            }

            // 自定义复选框样式
            :deep(.el-checkbox) {
                .el-checkbox__input.is-checked .el-checkbox__inner {
                    background-color: #0ccfa3;
                    border-color: #0ccfa3;
                }

                .el-checkbox__inner {
                    width: 20px;
                    height: 20px;
                }

                .el-checkbox__inner::after {
                    width: 6px;
                    height: 10px;
                    left: 6px;
                    top: 1px;
                    border-width: 2px;
                }

                .el-checkbox__inner:hover {
                    border-color: #0ccfa3;
                }

                .el-checkbox__label {
                    color: #979ea5;
                    font-size: 16px;
                }
            }

        }
    }
}
</style>
